clear all
set more off, perm
set maxvar 120000
set varabbrev off
* ---------------------------------------------- *
global dir 	"`1'"
global Data 	$dir/Data
global Tables 	$dir/Tables
global Figures 	$dir/Figures
global Work 	$dir/Work
global Temp 	$dir/Temp
global Pseudo	$dir/Work/Temp
* ---------------------------------------------- *
import sas $dir/Data/CRSP/msf.sas7bdat, clear case(lower)
keep if year(date)>=1980
gen mcap=abs(prc)*shrout if prc!=-99.0

tempfile crsp
save "`crsp'", replace
* ************************************************
* figure out whether security is common stock
import sas $dir/Data/CRSP/stocknames.sas7bdat, clear case(lower)
keep permno permco comnam namedt nameenddt siccd shrcd exchcd 
sort permco permno nameenddt

* find end-of-the-month day for the last record of each stock
by permco permno:  gen obs=_n
by permco permno:  gen tot=_N
replace nameenddt=mdy(12,31,year(nameenddt)) 			if month(nameenddt)==12 & obs==tot
replace nameenddt=mdy(month(nameenddt)+1,1,year(nameenddt))-1 	if month(nameenddt)<=11 & obs==tot
keep permco permno namedt nameenddt exchcd shrcd
* ************************************************
joinby permco permno using "`crsp'"
keep if date>=namedt & date<=nameenddt

* Ken's website: The six portfolios used to construct Mom each month include NYSE, AMEX, and NASDAQ stocks with prior return data. 
keep if exchcd>=1 & exchcd<=3
keep if shrcd==10 | shrcd==11
drop namedt nameenddt shrcd 

* Ken forms portfolios at t-1.  I form them at t.  I modify Kens' approach as appropriate
* Ken's website: To be included in a portfolio for month t, a stock must have a price for the end of month t-13 and a good return for t-2.
gen datem=mofd(date)
format datem %tm
tsset permno datem
keep if L12.prc+L1.ret<.
keep if L12.prc!=-99  

* Ken's website:  Each included stock also must have ME for the end of month t-1.
keep if mcap<. & mcap>0

gen L12ret=1
forvalues x=1(1)11 {
	quietly: replace L12ret=L12ret*(1+L`x'.ret) 	if L`x'.ret<.
}
* Ken's website: In addition, any missing returns from t-12 to t-3 must be -99.0, CRSP's code for a missing price. 
* This requirement is hard to implement --> stocknames.sas7bdat has values set to missing when appropriate (i.e. codes for missing values have been replaced by ".")
* In practice, it is extremely rare for returns to be missing while prices are not.
count if ret==. & prc!=.

forvalues x=2(1)11 {
	quietly: replace L12ret=. if L`x'.ret==. & L`x'.prc<.
}

bys datem: astile MOME = L12ret, qc(exchcd==1) nq(10)

keep permco permno datem MOME L12ret
* ***********************************
save $Work/MOME, replace
